package com.pinyougou.shop.controller;

import com.pinyougou.pojo.Result;
import com.tensquare.util.FastDFSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class UploadController {

    @Value("${FILE_SERVER_URL}")
    private String FILE_SERVER_URL;

    @RequestMapping("upload")
    public Result upload(MultipartFile file) throws Exception {
        try {
            //得到原始上传文件名
            String originalFilename = file.getOriginalFilename();
            //得到后缀名
            int i = originalFilename.lastIndexOf(".");
            //得到最后一个.的下标
            String substring = originalFilename.substring(i+1);
            //得到FastDFSClient对象，通过配置文件
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:config/fastdfs.conf");
            //进行上传，返回一个url地址
            String urll = fastDFSClient.uploadFile(file.getBytes(), substring);
            String url=FILE_SERVER_URL+urll;
            System.out.println("url = " + url);
            //返回
            return new Result(true,url);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"上传文件失败!");
        }


    }
}
